import React, { useState, useEffect } from 'react';
import { useSelector } from 'react-redux';
import { RootState } from '@/store';
import { getDraftWithUrls, DraftWithUrlsResponse } from '@/services/draftWithUrls';
import LayerContainer from './LayerContainer';
import TrackLayer from './TrackLayer';

const LayerSystem: React.FC = () => {
    const currentDraft = useSelector((state: RootState) => state.drafts.currentDraft);
    const [draftData, setDraftData] = useState<DraftWithUrlsResponse['data'] | null>(null);
    const [loading, setLoading] = useState(true);

    useEffect(() => {
        const fetchDraftData = async () => {
            if (!currentDraft?.id) {
                return;
            }

            try {
                setLoading(true);
                const response = await getDraftWithUrls(currentDraft.id);
                setDraftData(response);
            } catch (error) {
                console.error('获取草稿数据失败:', error);
            } finally {
                setLoading(false);
            }
        };

        fetchDraftData();
    }, [currentDraft?.id]);

    if (loading) {
        return (
            <div className="layer-system loading">
                <div className="loading-text">加载中...</div>
            </div>
        );
    }

    if (!draftData) {
        return (
            <div className="layer-system error">
                <div className="error-text">数据加载失败</div>
            </div>
        );
    }

    const tracks = draftData.script_content?.tracks || [];

    // 按 render_index 排序轨道（创建副本避免修改原数组）
    const sortedTracks = [...tracks].sort((a: any, b: any) => {
        const aRenderIndex = a.segments[0]?.render_index || 0;
        const bRenderIndex = b.segments[0]?.render_index || 0;
        return aRenderIndex - bRenderIndex;
    });

    return (
        <div className="layer-system">
            {sortedTracks.map((track: any) => {
                const renderIndex = track.segments[0]?.render_index || 0;
                return (
                    <LayerContainer key={track.id} renderIndex={renderIndex}>
                        <TrackLayer track={track} draftData={draftData} />
                    </LayerContainer>
                );
            })}
        </div>
    );
};

export default LayerSystem;
